import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

export interface DeviceSubType {
  classification_name: string;
  classification_code: string;
  specialty: string;
  device_count: number;
  naming_table?: string;
  position_table?: string;
  base_params_table?: string;
  naming_table_display?: string;
  position_table_display?: string;
  base_params_table_display?: string;
}

export interface DeviceCategoryHierarchy {
  category_name: string;
  specialty: string;
  total_device_count: number;
  subtypes: DeviceSubType[];
}

// GET /api/device-categories-hierarchy?specialty=配管专业
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const specialty = searchParams.get('specialty');
    
    const db = getDeviceParameterDb();
    
    // 从devices表获取设备分类统计
    let query = `
      SELECT 
        classification_name,
        classification_code,
        specialty,
        COUNT(*) as device_count
      FROM devices 
      WHERE classification_name IS NOT NULL 
        AND classification_name != ''
    `;
    
    const params: any[] = [];
    
    if (specialty) {
      query += ' AND specialty = ?';
      params.push(specialty);
    }
    
    query += `
      GROUP BY classification_name, classification_code, specialty
      ORDER BY classification_name
    `;
    
    const deviceParameterDb = db as any;
    const stmt = deviceParameterDb.db.prepare(query);
    const subtypes = stmt.all(...params) as DeviceSubType[];
    
    // 为每个子类型获取表映射信息
    const subtypesWithMapping = subtypes.map(subtype => {
      // 尝试从device_type_mappings获取表映射信息
      const mapping = db.getDeviceTypeMapping(subtype.classification_code);
      
      if (mapping) {
        return {
          ...subtype,
          naming_table: mapping.naming_table,
          position_table: mapping.position_table,
          base_params_table: mapping.base_params_table,
          naming_table_display: extractTableCode(mapping.naming_table),
          position_table_display: extractTableCode(mapping.position_table),
          base_params_table_display: extractTableCode(mapping.base_params_table)
        };
      }
      
      return subtype;
    });
    
    // 按设备大类分组
    const categoryMap = new Map<string, DeviceSubType[]>();
    
    subtypesWithMapping.forEach(subtype => {
      const categoryName = getCategoryName(subtype.classification_name);
      
      if (!categoryMap.has(categoryName)) {
        categoryMap.set(categoryName, []);
      }
      
      categoryMap.get(categoryName)!.push(subtype);
    });
    
    // 转换为层次结构
    const hierarchies: DeviceCategoryHierarchy[] = Array.from(categoryMap.entries()).map(([categoryName, subtypes]) => ({
      category_name: categoryName,
      specialty: specialty || '',
      total_device_count: subtypes.reduce((sum, st) => sum + st.device_count, 0),
      subtypes: subtypes.sort((a, b) => a.classification_name.localeCompare(b.classification_name))
    }));
    
    return NextResponse.json({
      success: true,
      data: hierarchies.sort((a, b) => a.category_name.localeCompare(b.category_name))
    });
    
  } catch (error) {
    console.error('获取设备分类层次失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取设备分类层次失败'
    }, { status: 500 });
  }
}

// 根据设备名称推导设备大类
function getCategoryName(classificationName: string): string {
  if (classificationName.includes('泵')) {
    return '泵类设备';
  } else if (classificationName.includes('阀')) {
    return '阀类设备';
  } else if (classificationName.includes('储罐') || classificationName.includes('容器')) {
    return '容器设备';
  } else if (classificationName.includes('管') || classificationName.includes('管道') || classificationName.includes('管线')) {
    return '管道设备';
  } else if (classificationName.includes('消防') || classificationName.includes('泡沫') || classificationName.includes('冷却')) {
    return '消防设备';
  } else if (classificationName.includes('污水') || classificationName.includes('处理')) {
    return '处理设备';
  } else if (classificationName.includes('过滤') || classificationName.includes('阻火')) {
    return '过滤设备';
  } else if (classificationName.includes('设备')) {
    return classificationName; // 已经是设备类别
  }
  
  // 默认分类
  return '其他设备';
}

// 从表名提取显示代码，如 "table_c2" -> "C.2"
function extractTableCode(tableName: string): string {
  if (!tableName) return '';
  const match = tableName.match(/table_c(\d+)/i);
  return match ? `C.${match[1]}` : tableName;
}